package com.next

class Contact
{
    boolean active = true

    /** **************************************************************************************************/

    Date createdDate = new Date()
    Date modifiedDate = new Date()

    ContactType type

    String fullName
    String cellphone
    String maritalStatus = "未婚"

    Salutation salutation
    //称谓

    String job

    String title
    //头衔

    String email
    String phone
    String fax
    String wechat
    String qq
    Date birthday
    //生日
    String hometown
    //家乡
    String hobby
    //爱好
    String taboo
    //禁忌

    Boolean cellphoneHasVerified = false
    String verifiedCode

    String password

    City city

    String idNumber

    String avatar

    String userCode
    String openId

    String appSessionId

    ContactLevel level

    Date lastLoginTimestamp = new Date()

    String externalId

    Country country
    //国籍

    Lead lead

    Date hireDate
    //入职时间
    Date leaveDate
    //离职时间

    String gender

    User user
    User createBy
    User modifyBy

    Territory territory

    LeadSource source

    static belongsTo = [account: Account]

    static hasMany = [certificates: ContactLoginCertificate, address: Address, notes: Note, attachments: Attachment, users: ContactTeam]

    static constraints = {
        cellphone blank: true, nullable: true
        cellphone matches: /^1\d{10}$/
        city blank: true, nullable: true
        maritalStatus inList: ["未婚", "已婚", "再婚", "离异", "丧偶"], blank: true, nullable: true
        idNumber blank: true, nullable: true
        verifiedCode blank: true, nullable: true
        user blank: true, nullable: true
        password blank: true, nullable: true
        avatar blank: true, nullable: true
        openId blank: true, nullable: true
        appSessionId blank: true, nullable: true, size: 0..256

        externalId maxSize: 32, blank: true, nullable: true //, unique: true
        country nullable: true, blank: true

        lead blank: true, nullable: true
        user blank: true, nullable: true
        createBy blank: true, nullable: true
        modifyBy blank: true, nullable: true
        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true
        lastLoginTimestamp nullable: true, blank: true

        fax nullable: true, blank: true
        title nullable: true, blank: true
        userCode nullable: true, blank: true
        email nullable: true, blank: true
        salutation nullable: true, blank: true
        phone nullable: true, blank: true

        territory nullable: true, blank: true
        level nullable: true, blank: true

        wechat maxSize: 32, nullable: true, blank: true
        qq maxSize: 32, nullable: true, blank: true

        hometown maxSize: 32, nullable: true, blank: true
        hobby maxSize: 32, nullable: true, blank: true
        taboo maxSize: 32, nullable: true, blank: true
        hireDate nullable: true, blank: true
        leaveDate nullable: true, blank: true
        birthday nullable: true, blank: true

        job maxSize: 32, nullable: true, blank: true

        gender inList: ['男', '女'], nullable: true, blank: true

        source nullable: true, blank: true
    }

    static mapping = {
        sort 'fullName'
    }

    String toString()
    {
        if (account)
        {
            return "${account} - ${fullName}"
        }
        else
        {
            return fullName
        }
    }

    def springSecurityService

    def beforeInsert()
    {
        def username = springSecurityService?.getPrincipal()?.username
        createBy = User.findByUsername(username)
        if (!user)
        {
            user = createBy
        }

        def company = Company.findAll()[0]
        if (company.enableAccountTerritory && company.enableContactTerritory && company.inheritanceAccountTerritory)
        {
            territory = account.territory
        }

        if (territory)
        {
            def territoryTeam = TerritoryTeam.findAllByTerritory(territory)
            territoryTeam?.each {
                def contactTeam = new ContactTeam(contact: this, user: it.user, teamRole: it.teamRole,
                                                  contactPermission: it?.contactPermission,
                                                  activityPermission: it?.activityPermission,
                                                  teamPermission: it?.teamPermission,
                                                  attachmentPermission: it?.attachmentPermission,
                                                  notePermission: it?.notePermission,
                                                  flexFieldPermission: it?.flexFieldPermission,
                                                  addressPermission: it?.addressPermission)
                this.addToUsers(contactTeam)
            }
        }

        if (user.shareContactToSupervisor)
        {
            User reportTo = user.reportTo

            while (reportTo)
            {
                def flag = true
                users?.each {
                    if (reportTo == it?.user)
                    {
                        flag = false
                    }
                }

                if (flag)
                {
                    ContactTeam contactTeam = new ContactTeam(contact: this, user: reportTo,
                                                              teamRole: TeamRole.findByName('Read'),
                                                              contactPermission: TeamRole.findByName('Read'),
                                                              activityPermission: TeamRole.findByName('Read'),
                                                              teamPermission: TeamRole.findByName('Read'),
                                                              attachmentPermission: TeamRole.findByName('Read'),
                                                              notePermission: TeamRole.findByName('Read'),
                                                              flexFieldPermission: TeamRole.findByName('Read'),
                                                              addressPermission: TeamRole.findByName('Read'))
                    this.addToUsers(contactTeam)
                }

                reportTo = reportTo.reportTo
            }
        }

        // 初始化 所有者 权限
        def flag = true
        users?.each {
            if (user == it?.user)
            {
                flag = false
            }
        }

        if (flag)
        {
            ContactTeam contactTeam = new ContactTeam(contact: this,
                                                      user: user,
                                                      teamRole: TeamRole.findByName('Edit'),
                                                      contactPermission: TeamRole.findByName('Edit'),
                                                      activityPermission: TeamRole.findByName('Edit'),
                                                      teamPermission: TeamRole.findByName('Edit'),
                                                      attachmentPermission: TeamRole.findByName('Edit'),
                                                      notePermission: TeamRole.findByName('Edit'),
                                                      flexFieldPermission: TeamRole.findByName('Edit'),
                                                      addressPermission: TeamRole.findByName('Edit'))
            this.addToUsers(contactTeam)
        }
    }

    def afterInsert()
    {
        def flexFieldCategories = FlexFieldCategory.findAllByObjectType('Contact')
        flexFieldCategories?.each {
            if (it?.condition)
            {
                def result = false
                try
                {
                    def shell = new GroovyShell()
                    def closure = shell.evaluate(it?.condition?.script)
                    result = closure(this)
                }
                catch (Exception e)
                {
                    log.error e
                }
                if (result)
                {
                    initFlexField(it)
                }
            }
            else
            {
                initFlexField(it)
            }
        }

    }

    def initFlexField(FlexFieldCategory flexFieldCategory)
    {
        def fields = FlexField.findAllByCategory(flexFieldCategory)
        fields?.each {
            def field = new FlexFieldInstance(category: flexFieldCategory, field: it, contact: this)
            field.save()
        }
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)
    }
}
